<template>
  <el-autocomplete v-bind="$attrs"
                   v-model="val"
                   :fetch-suggestions="querySearchAsync"
                   @select="handleSelect" />
</template>

<script>
export default {
  name: 'FormInputAutocomplete',
  props: {
    // 请求地址
    ajaxObj: {
      type: Object
    },
    value: {
      required: true
    }
  },
  data () {
    return {
      val: this.value,
      selectItem: {},
      query: 'name'
    }
  },
  watch: {
    // value (newVal, oldVal) {
    //   console.log('new', newVal, oldVal)
    //   if (newVal && newVal !== oldVal) {
    //     if (newVal === this.selectItem.id) {
    //       this.val = this.selectItem.value
    //     } else {
    //       this.val = newVal
    //     }
    //   } else {
    //     this.val = newVal
    //   }
    // }
    value: {
      handler (newVal, oldVal) {
        // 解决监听不及时导致缓存上一次输入内容问题
        if (newVal && newVal !== oldVal) {
          if (newVal === this.selectItem.id) {
            this.val = this.selectItem.value
          } else {
            this.val = newVal
          }
        } else {
          this.val = newVal
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 搜索
    querySearchAsync (queryString, callback) {
      if (this.ajaxObj.keys) {
        this.query = this.ajaxObj.keys
      } else {
        this.query = 'name'
      }
      if (!queryString) this.clearCurItemHandle()
      const params = {
        ...this.ajaxObj.params
        // name: queryString
      }
      if (this.ajaxObj.params && this.ajaxObj.params.params) {
        params.params[this.query] = queryString
      } else {
        params[this.query] = queryString
      }
      this.$axios[this.ajaxObj.method || 'get'](this.ajaxObj.url, this.ajaxObj.method ? params : { params })
        .then(res => {
          if (res.data.meta.success) {
            const resData = this.ajaxObj.dataHandle && typeof this.ajaxObj.dataHandle === 'function' ? this.ajaxObj.dataHandle(res) : this.ajaxObj.deep ? res.data.data : res.data.data.data
            const dataArr = resData.map(item => ({ ...item, value: item.name }))
            callback(dataArr)
          }
        })
    },
    handleSelect (item) {
      this.selectItem = item
      this.$emit('change', item.id)
      this.$emit('getAutoDetail', item)
    },
    clearCurItemHandle () {
      this.selectItem = {}
      this.$emit('change', null)
    }
  }
}
</script>

<style scoped>
</style>
